// 基于uni.storage的本地存储封装
const PREFIX = 'moolio_'

class StorageUtil {
  // 设置存储
  static set(key, value, expire = null) {
    const fullKey = PREFIX + key
    if (expire) {
      const expireTime = Date.now() + expire * 1000
      uni.setStorageSync(fullKey, {
        value,
        expire: expireTime
      })
    } else {
      uni.setStorageSync(fullKey, value)
    }
  }

  // 获取存储
  static get(key, defaultValue = null) {
    const fullKey = PREFIX + key
    try {
      const data = uni.getStorageSync(fullKey)
      
      if (data === null || data === undefined) {
        return defaultValue
      }
      
      // 检查是否过期
      if (data && typeof data === 'object' && data.expire) {
        if (Date.now() > data.expire) {
          uni.removeStorageSync(fullKey)
          return defaultValue
        }
        return data.value
      }
      
      return data
    } catch (error) {
      return defaultValue
    }
  }

  // 删除存储
  static remove(key) {
    const fullKey = PREFIX + key
    uni.removeStorageSync(fullKey)
  }

  // 清空所有存储
  static clear() {
    uni.clearStorageSync()
  }

  // 检查是否存在
  static has(key) {
    const fullKey = PREFIX + key
    try {
      const data = uni.getStorageSync(fullKey)
      return data !== null && data !== undefined
    } catch (error) {
      return false
    }
  }

  // 获取所有键名
  static keys() {
    try {
      const info = uni.getStorageInfoSync()
      return info.keys.filter(key => key.startsWith(PREFIX))
    } catch (error) {
      return []
    }
  }
}

// 为了兼容request.js的导入方式，添加独立的函数导出
export const getStorage = (key, defaultValue = null) => {
  return StorageUtil.get(key, defaultValue)
}

export const setStorage = (key, value, expire = null) => {
  StorageUtil.set(key, value, expire)
}

export const removeStorage = (key) => {
  StorageUtil.remove(key)
}

export const clearStorage = () => {
  StorageUtil.clear()
}

// 保持原有默认导出
export default StorageUtil